package top.tomxwd.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import top.tomxwd.springcloud.pojo.Dept;
import top.tomxwd.springcloud.service.DeptService;

import java.util.List;

/**
 * @author xieweidu
 * @createDate 2020-06-05 22:49
 */
@RestController
@Slf4j
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept) {
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "processHystrixGet")
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = deptService.queryById(id);
        if (dept == null) {
            throw new RuntimeException("12345");
        }
        return dept;
    }

    /**
     * getbyid熔断器用
     *
     * @param id
     * @return
     */
    public Dept processHystrixGet(@PathVariable("id") Long id) {
        return new Dept().setDeptno(id).setDname("该ID: " + id + "没有找到对应的信息,null--@HystrixCommand")
                .setDbSource("no this database in MySQL");
    }

    @GetMapping("/dept/list")
    public List<Dept> queryAll() {
        return deptService.queryAll();
    }

    /**
     * 注册进来的微服务，获取应用信息
     *
     * @return
     */
    @GetMapping("/info")
    public Object discovery() {
        // 获取微服务列表清单
        List<String> services = discoveryClient.getServices();
        log.info("微服务列表清单：{}", services);

        // 获取一个具体的微服务实例 通过serviceId,就是app.name
        List<ServiceInstance> instances = discoveryClient.getInstances(services.get(0));
        instances.forEach(instance -> {
            log.info("instance.getUri() = {}", instance.getUri());
            log.info("instance.getPort() = {}", instance.getPort());
            log.info("instance.getHost() = {}", instance.getHost());
            log.info("instance.getInstanceId() = {}", instance.getInstanceId());
            log.info("instance.getMetadata() = {}", instance.getMetadata());
            log.info("instance.getScheme() = {}", instance.getScheme());
            log.info("instance.getServiceId() = {}", instance.getServiceId());
        });

        // 应用描述信息
        String description = discoveryClient.description();
        log.info("应用描述信息{}", description);
        return null;
    }

}
